<?php

namespace Xp130\Rank;

use Exception;
use PDO;

class Installer
{
    public static function install(): void
    {
        $sqlFile = __DIR__ . '/../sql/init_rank_db.sql';
        if (!file_exists($sqlFile)) {
            echo "未找到 SQL 文件.\r\n";
        }
        try {
            $config = (new ConfigLoader())->load()['mysql'];
            $dsn = sprintf(
                '%s:host=%s;port=%s;dbname=%s;charset=%s',
                $config['driver'],
                $config['host'],
                $config['port'],
                $config['database'],
                $config['charset']
            );
            $pdo = new PDO(
                $dsn,
                $config['username'],
                $config['password'],
                [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]
            );
            // 读取SQL文件并执行
            $sql = file_get_contents($sqlFile);
            $pdo->exec($sql);

            echo "SQL 文件已成功执行。\r\n";
        } catch (Exception $e) {
            echo '执行 SQL 文件时出错: ' . $e->getMessage() . "\r\n";
        }

    }
}